import asyncio
import websockets
import base64
import cv2
import numpy as np


async def video_stream(websocket):
    # 移除了 'path' 参数
    capture = cv2.VideoCapture(0)
    if not capture.isOpened():
        print("Cannot open camera")
        return

    encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 80]

    try:
        while True:
            ret, frame = capture.read()
            if not ret:
                print("无法读取摄像头画面")
                break

            # 将图像编码为JPEG并转换为base64
            result, imgencode = cv2.imencode('.jpg', frame, encode_param)
            if not result:
                print("图像编码失败")
                continue

            data = np.array(imgencode)
            img = base64.b64encode(data).decode('utf-8')

            # 发送base64编码的图像
            await websocket.send("data:image/jpeg;base64," + img)
            await asyncio.sleep(0.1)
    except Exception as e:
        print(f"发生错误: {e}")
    finally:
        capture.release()
        print("摄像头已释放")


async def main():
    # 注意：这里也移除了 path 参数
    async with websockets.serve(video_stream, "0.0.0.0", 8168):
        print("WebSocket server is running on ws://0.0.0.0:8168")
        print("等待客户端连接...")
        await asyncio.Future()  # 永久运行


if __name__ == "__main__":
    asyncio.run(main())